﻿using CheatMenu.Utils;
using Fungus;
using HarmonyLib;
using System.Collections;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

namespace CheatMenu.Patch
{
    public class AsyncLoadScenePatcher
    {
        public static bool Enabled { get; set; }

        public static void Patch(Harmony harmony)   
        {
            BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
            var original = typeof(SceneLoader).GetMethod("Start", bindingFlags);
            var prefix = typeof(AsyncLoadScenePatcher).GetMethod("prefix_Start");
            harmony.Patch(original, new HarmonyMethod(prefix), null);
        }

        public static bool prefix_Start(SceneLoader __instance)
        {
            if (Enabled)
            {
                __instance.StartCoroutine((new AsyncLoadScenePatcher(ReflectionUtil.GetSceneToLoad(__instance))).DoLoadBlock());
                return false;
            }
            else
            {
                return true;
            }
        }

        protected virtual IEnumerator DoLoadBlock()
        {
            Text m_Text = GameObject.Find("Day")?.GetComponent<Text>();
            AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(this.sceneToLoad);
            do
            {
                if (m_Text) m_Text.text = "Loading: " + ((int)(asyncLoad.progress * 100)).ToString() + "%";
                yield return new WaitForEndOfFrame();
            } while (!asyncLoad.isDone);
            yield break;
        }

        public AsyncLoadScenePatcher(string sceneToLoad)
        {
            this.sceneToLoad = sceneToLoad;
        }

        protected string sceneToLoad;
    }
}
